﻿using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace AutoUpdater.Util
{
    public class XElementAchieve
    {
        private const string Skey = @"\L6?}???";

        public static XElement GetXml(string filePath, bool encode = false)
        {
            if (!encode)
            {
                return XElement.Load(filePath);
            }

            XElement xmlDoc = null;
            var des = new DESCryptoServiceProvider
            {
                Key = Encoding.ASCII.GetBytes(Skey),
                IV = Encoding.ASCII.GetBytes(Skey)
            };
            ICryptoTransform desdecrypt = des.CreateDecryptor();
            using (var fsread = new FileStream(filePath,
                FileMode.Open,
                FileAccess.Read))
            using (var cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read))
            {
                var reader = new XmlTextReader(cryptostreamDecr);
                xmlDoc = XElement.Load(reader);
            }
            return xmlDoc;
        }

        public static void SaveXml(XElement xmlDoc, string filePath, bool encode = false)
        {
            if (!encode)
            {
                xmlDoc.Save(filePath);
                return;
            }

            var des = new DESCryptoServiceProvider
            {
                Key = Encoding.ASCII.GetBytes(Skey),
                IV = Encoding.ASCII.GetBytes(Skey)
            };
            ICryptoTransform desencrypt = des.CreateEncryptor();

            using (var fsEncrypted = new FileStream(filePath,
                FileMode.Create,
                FileAccess.Write))
            using (var cryptostream = new CryptoStream(fsEncrypted,
                desencrypt,
                CryptoStreamMode.Write))
            {
                //将文档保存到本地
                xmlDoc.Save(cryptostream);
            }

        }
    }
}
